﻿using LcAudit.BPM.Core.Dal;
using LcAudit.BPM.Core.Model;
using LcAudit.Common;
using LcAudit.Common.Data;
using LcAudit.Common.Data.Filter;
using LcAudit.Common.Data.SqlServer;
using LcAudit.Common.Provider;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace LcAudit.BPM.Core.Bll
{
    public class bidderinfoBll
    {
        private double borderNumber = 0.5;
        //private string corpusFolder = Application.StartupPath;
        /// <summary>
        /// 语料文件名
        /// </summary>
        private List<string> fileNames = new List<string>();
        /// <summary>
        /// 降维表
        /// </summary>
        private List<string> reducingKeys = new List<string>();
        /// <summary>
        /// 文章的词典（降维后）
        /// </summary>
        private Dictionary<string, Dictionary<string, int>> textsDictionaries = new Dictionary<string, Dictionary<string, int>>();
        //Dictionary<string, int> wordFrequency = new Dictionary<string, int>();
        public static bidderinfoBll Instance
        {
            get { return SingletonProvider<bidderinfoBll>.Instance; }
        }

        public string Add(bidderinfo u)
        {
            int uid = 0;
            string msg = "添加失败！";
            uid = bidderinfoDal.Instance.Insert(u, new string[] { "keyid", "binputtime" });
            if (uid > 0)
            {
                msg = "添加成功！";
            }

            return new JsonMessage { Data = uid.ToString(), Message = msg, Success = uid > 0 }.ToString();
        }

        public string Edit(bidderinfo u)
        {
            int k;
            string msg = "编辑失败。";
            u.binputtime = DateTime.Now;
            k = bidderinfoDal.Instance.Update(u);
            if (k > 0)
            {
                msg = "编辑成功。";
            }

            return new JsonMessage { Data = k.ToString(), Message = msg, Success = k > 0 }.ToString();
        }

        public string Delete(int Id)
        {
            string msg = "删除失败！";
            int k = 0;

            k = bidderinfoDal.Instance.Delete(Id);
            if (k > 0)
            {
                msg = "删除成功。";
            }

            return new JsonMessage { Data = k.ToString(), Message = msg, Success = k > 0 }.ToString();
        }
        public int AddBidderToBag(int bagid, string bidders)
        {

            if (string.IsNullOrEmpty(bidders))
                return 0;
            var roleIdList = bidders.Split(',').Select(n => PublicMethod.GetInt(n)).ToArray();
            return bidderinfoDal.Instance.AddBidderTo(bagid, roleIdList);
        }
        public string Ftxt(int bid, string ftxt)
        {
            baginfo bag = baginfoDal.Instance.Get(bid);
            int filenum = 0;
            StringBuilder gudong = new StringBuilder();
            IEnumerable<bagbidder> bagbidders = bagbidderDal.Instance.GetWhere(new { bagid = bid }).ToList();
            List<bidderinfo> bidders = new List<bidderinfo>();
            foreach (var bb in bagbidders)
            {
                bidders.Add(bidderinfoDal.Instance.Get(bb.bid));
            }
            foreach (var bb in bidders)
            {
                int num = 0;
                //文件查找
                string files = "";
                FileInfo f = null;

                files = HttpContext.Current.Server.MapPath("/upload/" + bag.bagbh +bag.KeyId+ "/" + bb.KeyId + ".doc");
                f = new FileInfo(files);
                if (f.Exists)
                {
                    if (LcAudit.Common.ExWord.ExportToWordExped(ftxt, files))
                        gudong.AppendFormat("投标商“{0}”方案中存在“{1}”文本<br/>", bb.bname, ftxt);
                }
            }
            string re = gudong.ToString() + "<br/>";
            return new JsonMessage { Data = "", Message = re, Success = true }.ToString();
        }
        public string GetBidderName(string file)
        {
            string idstr = file.Substring(file.LastIndexOf('\\') + 1, file.Length);
            int id = 0;
            int.TryParse(idstr,out id);
           return  bidderinfoDal.Instance.Get(id).bname;
        }
        public string AuditBag(int bid)
        {
            baginfo bag = baginfoDal.Instance.Get(bid);
            DateTime dt = bag.tbdate;
            decimal fileavg = 0;
            int filenum = 0;
            StringBuilder gudong = new StringBuilder();//股东
            
            StringBuilder cldate = new StringBuilder();//成时间
            
            StringBuilder agent = new StringBuilder();//代理人
            
            StringBuilder manager = new StringBuilder();//项目经理
            
            StringBuilder add = new StringBuilder();//地区
            
            StringBuilder filen = new StringBuilder();//大小
            
            StringBuilder filet = new StringBuilder();//时间
            
            IEnumerable<bagbidder> bagbidders = bagbidderDal.Instance.GetWhere(new { bagid = bid }).ToList();
            List<bidderinfo> bidders = new List<bidderinfo>();
            foreach (var bb in bagbidders)
            {
                bidders.Add(bidderinfoDal.Instance.Get(bb.bid));
            }
            foreach (var bb in bidders)
            {
                string files = HttpContext.Current.Server.MapPath("/upload/" + bag.bagbh +bag.KeyId+ "/" + bb.KeyId + ".doc");
                FileInfo f = new FileInfo(files);
                if (f.Exists)
                {
                    filenum++;
                    fileavg += (decimal)f.Length / 1024;
                }
            }
            if (filenum != 0)
                fileavg = fileavg / filenum;
            foreach (var bb in bidders)
            {
                string gd = bb.bshareholders;
                string[] gds = gd.Split(',');
                if (Math.Abs(dt.Subtract(bb.bdatetime).Duration().Days) <= 90)
                    cldate.AppendFormat("投标商“{0}”成立时间“{1}”与投标时间“{2}”太近<br/>", bb.bname, bb.bdatetime.ToLocalTime(), dt.ToLocalTime());
                int num = 0;
                //文件查找
                string files = "";
                FileInfo f = null;
                if (filenum > 0)
                {
                    files = HttpContext.Current.Server.MapPath("/upload/" + bag.bagbh + bag.KeyId + "/" + bb.KeyId + ".doc");
                    f = new FileInfo(files);
                    if (f.Exists)
                    {
                        if (fileavg * (decimal)0.6 > (decimal)f.Length / 1024)
                        {
                            filen.AppendFormat("投标商“{0}”文档方案太小<br/>", bb.bname);
                        }
                    }
                }
                foreach (var b in bidders)
                {
                    if (bb.bname != b.bname)
                    {
                        if (bb.bhuji == b.bhuji)
                        {
                            num++;
                        }
                        foreach (string g in gds)
                        {
                            string[] bgds = b.bshareholders.Split(',');
                            foreach(string bg in bgds)
                            if (bg==g)
                            {
                                gudong.AppendFormat("投标商“{0}”与投标商“{1}”有相同的股东“{2}”<br/>", bb.bname, b.bname, g);
                            }
                        }
                        if (filenum > 0)
                        {
                            string filebs = HttpContext.Current.Server.MapPath("/upload/" + bag.bagbh + bag.KeyId + "/" + b.KeyId + ".doc");
                            FileInfo fb = new FileInfo(filebs);
                            if (fb.Exists)
                            {
                                if (f.CreationTime.ToShortDateString() == fb.CreationTime.ToShortDateString())
                                    filet.AppendFormat("投标商“{0}”与投标商“{1}”文档创建时间一样“{2}”<br/>", bb.bname, b.bname, f.CreationTime);

                            }

                        }
                    }
                    
                }
                //项目、代理
                string agid = bb.Agent.aidno;
                string maid = bb.Manager.midno;
                DataTable adt = SqlEasy.ExecuteDataTable("select bname from vbidder where bname<>'" + bb.bname + "' and aidno='" + agid + "'");
                if (adt.Rows.Count > 0)
                {
                    for (int i = 0; i < adt.Rows.Count; i++)
                        agent.AppendFormat("投标商“{0}”代理人“{1}”代理过投标商“{2}”<br/>", bb.bname, bb.Agent.aname, adt.Rows[i][0].ToString());

                }
                adt = SqlEasy.ExecuteDataTable("select bname from vbidder where bname<>'" + bb.bname + "' and midno='" + maid + "'");
                if (adt.Rows.Count > 0)
                {
                    for (int i = 0; i < adt.Rows.Count; i++)
                        agent.AppendFormat("投标商“{0}”项目经理“{1}”做过投标商“{2}”的项目经理<br/>", bb.bname, bb.Manager.mname, adt.Rows[i][0].ToString());
                }
                if (num > 2)
                    add.AppendFormat("投标商“{0}”与“{1}”家投标商来自同一地点“{2}”<br/>", bb.bname, num, bb.bhuji);

            }
            GetAllDirectories(HttpContext.Current.Server.MapPath("/upload/" + bag.bagbh + bag.KeyId));
            string bdresult=SeparateIntoPairs();
            string priceCompareResult = priceCompare();
            string re = "<span class='rtitle'>投标商股东的审查结果：</span><br/>"+gudong.ToString() 
                + "<br/>" +"<span class='rtitle'>投标商成立时间审查结果：</span><br/>"+ cldate.ToString() 
                + "<br/>" +"<span class='rtitle'>投标商代理人审查结果：</span><br/>"+ agent.ToString() 
                + "<br/>" +"<span class='rtitle'>投标商项目经理审查结果：</span><br/>"+ manager.ToString()
                + "<br/>" + "<span class='rtitle'>投标商中所在地区审查结果：</span><br/>"+add.ToString() 
                + "<br/>" +"<span class='rtitle'>投标商方案文档大小审查结果：</span><br/>"+ filen.ToString() 
                + "<br/>" +"<span class='rtitle'>投标商方案文档时间审查结果：</span><br/>"+ filet.ToString() 
                + "<br/>" +"<span class='rtitle'>投标商方案文档相似度审查结果：</span><br/>"+ bdresult
                + "<br/>" + "<span class='rtitle'>投标商价格比对审查结果：</span><br/>"+priceCompareResult;
            string file = ExWord.ExportFile(gudong.ToString().Replace("<br/>", "\r\n"),
                cldate.ToString().Replace("<br/>", "\r\n"),
                agent.ToString().Replace("<br/>", "\r\n"), 
                manager.ToString().Replace("<br/>", "\r\n"),
                add.ToString().Replace("<br/>", "\r\n"),
                filen.ToString().Replace("<br/>", "\r\n"), 
                filet.ToString().Replace("<br/>", "\r\n"), 
                bdresult.Replace("<br/>", "\r\n"),          
                bag.bagname, 
                bag.bagbh,     
                priceCompareResult.Replace("<br/>", "\r\n"));
            return new JsonMessage { Data = file, Message = re, Success = true }.ToString();
        }
        public void GetAllDirectories(string rootPath)
        {
            this.fileNames.Clear();            
            string[] files = System.IO.Directory.GetFiles(rootPath);//得到目录下所有的文件的名称(包括路径，非子目录)
            InAndOut.changwords(rootPath);
            SVMModle getKeys = new SVMModle(reducingKeys);
            string filename = string.Empty;
            this.textsDictionaries.Clear();
            foreach (string file in files)
            {
                if (file.ToLower().EndsWith(".txt"))
                {
                    filename = file.Substring(file.LastIndexOf('\\') + 1,
                        file.LastIndexOf('.') - file.LastIndexOf('\\') - 1);
                    this.fileNames.Add(filename);//将当前目录中的所有文件全名存入文件List，不包括扩展名
                    Dictionary<string, int> dictionary = getKeys.GetDictionary(InAndOut.ReadFile(file));
                    this.textsDictionaries.Add(filename, dictionary);//已添加了具有相同键的项。                    
                }
            }
        }
        public string  SeparateIntoPairs()
        {            
                double similarity = 0.0;
                SVMModle svmSimilarity = new SVMModle();
                DateTime start = DateTime.Now;
                string result="";
                //result = "<span class='rtitle'>投标商方案文档相似度审查结果：</span><br />";
                int k = 0;
                for (int i = 0; i < fileNames.Count; i++)
                {
                    similarity = 0.0;
                    for (int j = i + 1; j < fileNames.Count; j++)
                    {
                        //if (caculated.Contains(GetTag(i, j))) continue;
                        similarity = svmSimilarity.Similarity(textsDictionaries[fileNames[i]], textsDictionaries[fileNames[j]]);
                        //caculated.Add(GetTag(i, j));
                        if (similarity >= 0)
                        {
                            result += (++k).ToString() + "：" + GetBidderName(fileNames[i]) + "&"
                                + GetBidderName(fileNames[j]) + "@" + similarity.ToString("0.00")+"<br/>";
                        }
                    }                    
                }
                return result;
        }
        public string GetList()
        {
            var devList = bidderinfoDal.Instance.GetAll();
            var list = devList as List<bidderinfo> ?? devList.ToList();
            return list.Any() ? JSONhelper.ToJson(list) : "[]";
        }
        public string GetJsonData(int pageindex, int pagesize, string filterJson, string sort, string order)
        {
            var pcp = new ProcCustomPage("Vdistender")
            {
                PageIndex = pageindex,
                PageSize = pagesize,
                OrderFields = sort + " " + order,
                WhereString = FilterTranslator.ToSql(filterJson)
            };
            int recordCount;
            DataTable dt = bidderinfoDal.Instance.GetPageWithSp(pcp, out recordCount);
            return JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt);
        }

        private string priceCompare() 
        {
            string str = "";

            LcAudit.BPM.Core.Bll.materialprice mm = new  LcAudit.BPM.Core.Bll.materialprice ();

            DataSet ds_bid = mm.GetList(" select distinct bid from materialpriceinfo ", " 1=1 ");

            List<int> li_bid = new List<int>();

            if (ds_bid.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow r in ds_bid.Tables[0].Rows)
                {
                    li_bid.Add(Convert.ToInt32(r["bid"]));
                }
            }

            if (li_bid.Count > 0)
            {
                decimal price_i = 0;
                decimal price_j = 0;

                for (int i = 0; i < li_bid.Count; i++)
                {
                    for (int j = i+1; j < li_bid.Count; j++)
                    {
                        int bid_i = li_bid[i];
                        int bid_j = li_bid[j];

                        DataSet ds_i = mm.GetList(" select mpname,mpxh,mprice,bname,bagname from Vmaterialprice ", " bid=" + bid_i);

                        List<materialpriceinfo> li_price_compare = new List<materialpriceinfo>();

                        foreach (DataRow r in ds_i.Tables[0].Rows)
                        {
                            string mpname = r["mpname"].ToString();
                            string mpxh = r["mpxh"].ToString();
                            string bname = r["bname"].ToString();
                            string bagname = r["bagname"].ToString();
                            string bname_compare = "";
                            string bagname_compare = "";

                            price_i = Convert.ToDecimal(r["mprice"]);

                            DataSet ds_j = mm.GetList(" select mprice,bname,bagname from Vmaterialprice ", " bid= " + bid_j 
                                + " and mpname='"+mpname
                                +"' and mpxh='"+mpxh+"' ");

                            if (ds_j.Tables[0].Rows.Count == 1)
                            {
                                price_j = Convert.ToDecimal(ds_j.Tables[0].Rows[0]["mprice"]);
                                bagname_compare = ds_j.Tables[0].Rows[0]["bagname"].ToString();
                                bname_compare = ds_j.Tables[0].Rows[0]["bname"].ToString();

                            }

                            materialpriceinfo m = new materialpriceinfo();
                            m.bname = bname;
                            m.bagname = bagname;
                            m.bname_compare = bname_compare;
                            m.bagname_compare = bagname_compare;
                            m.mprice = (price_i - price_j) / price_i;
                            li_price_compare.Add(m);
                        }

                        decimal sum = 0;

                        foreach (materialpriceinfo c in li_price_compare)
                        {
                            sum += c.mprice.Value;
                        }

                        decimal avg = sum / li_price_compare.Count;

                        if (avg == li_price_compare[0].mprice.Value)
                        {
                            if (avg == 0)
                            {
                                str += " 投标商“" + li_price_compare[0].bname
                              + "” 与投标商“" + li_price_compare[0].bname_compare
                              + "” 在包名“" + li_price_compare[0].bagname
                              + "”存在价格异常，每项材料单价相同"+"\n\n" ;
                            }
                            else
                            {
                                str += " 投标商“" + li_price_compare[0].bname
                              + "” 与投标商“" + li_price_compare[0].bname_compare
                              + "” 在包名“" + li_price_compare[0].bagname
                              + "”存在价格梯度变化，每项材料单价变化" + Math.Abs(li_price_compare[0].mprice.Value * 100) + "%" + "\n\n";
                            }
                          
                        }
                    }
                }
            }
          
            return str;
        }

    }
}
